package com.jjty.dataGenerator.utils;

import com.jjty.dataGenerator.exception.ServiceException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import javax.servlet.http.HttpServletRequest;
import java.util.concurrent.TimeUnit;

/**
 * @Author: huangyulong
 * @createTime: 2023-04-12 16:40
 * @Description: Redis获取工具，在拦截器过滤器中无法直接注入
 */
@Component
public class RedisUtils {

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    public static RedisTemplate redis;

    public static StringRedisTemplate stringRedis;

    @PostConstruct
    public void init(){
        redis = redisTemplate;
        stringRedis = stringRedisTemplate;
    }


    public static boolean tryLock(String key,String value){
        Boolean b = stringRedis.opsForValue().setIfAbsent("base_lock:" + key, value, 10L, TimeUnit.SECONDS);
        return Boolean.TRUE.equals(b);
    }

    public static boolean tryLock(String key){
        return tryLock(key,"1");
    }

    public static String tryLockIp(HttpServletRequest request, String key){
        //加锁，幂等
        String externalIP = OtherUtils.getExternalIP(request);
        key = externalIP + "-" + key;
        boolean b = tryLock(key);
        if(!b){
            throw new ServiceException("请勿频繁操作！");
        }
        return key;
    }

    public static void releaseLock(String key){
        stringRedis.delete("base_lock:" + key);
    }

}
